package com.bjsj.pro;

import android.app.Activity;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.GcmRegister;
import com.alibaba.sdk.android.push.register.MeizuRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;
import com.allen.library.BuildConfig;
import com.bjsj.pro.tools.Configs;
import com.bjsj.pro.tools.GlobalTools;
import com.bjsj.pro.tools.RecordUtils;
import com.bjsj.pro.ui.MainActivity;
import com.bjsj.pro.R;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.store.PersistentCookieStore;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

import static anetwork.channel.download.DownloadManager.TAG;


/**
 * Created by Nevermore on 2018/7/6.
 * zhuApp
 */

public class TourismApp extends Application
{
    private static MainActivity mainActivity = null;
    public static TourismApp myApp = null;// 声明本类App对象,App程序全局使用
    private List<Activity> listActivity = null;// 创建Activity集合，用于存放Activity
    private Bitmap mScreenCaptureBitmap;
    private int vipflage=0;
    //static 代码段可以防止内存泄露
    static
    {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator()
        {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout)
            {

                layout.setPrimaryColorsId(R.color.white, android.R.color.black);//全局设置主题颜色

                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator()
        {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout)
            {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);

            }
        });

    }
    @Override
    public void onCreate()
    {
        super.onCreate();
        myApp = this;
      //  MobSDK.init(this);
        // 初始化存储所有的activity的集合
        listActivity = new ArrayList<Activity>();
        initCloudChannel(myApp);

        //必须调用初始化
        OkGo.init(this);
        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try
        {
            //以下都不是必须的，根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
            OkGo.getInstance()
                    //如果使用默认的 60秒,以下三行也不需要传
                    .debug("lcm")
                    .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS)  //全局的连接超时时间
                    .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS)     //全局的读取超时时间
                    .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS)    //全局的写入超时时间
                    //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
                    .setRetryCount(0)
                    //cookie使用内存缓存（app退出后，cookie消失）
                    .setCookieStore(new PersistentCookieStore());       //cookie持久化存储，如果cookie不过期，则一直有效

        } catch (Exception e)
        {
            e.printStackTrace();
        }


    }

    public static void initdata(){

        // JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(myApp);
        //录音库
        RecordUtils.init(myApp);
    }




    public static TourismApp getAppInstance()
    {
        return myApp;
    }

    /**
     * 构造方法描述:封装全局的存储所有的activity的集合get方法
     *
     * @return 返 回 类 型:List<Activity>
     */
    public List<Activity> getListActivity()
    {
        return listActivity;
    }

    /**
     * 构造方法描述:封装全局的存储所有的activity的集合set方法
     *
     * @param listActivity 返 回 类 型:void
     */
    public void setListActivity(List<Activity> listActivity)
    {
        this.listActivity = listActivity;
    }

    /**
     * 构造方法描述:添加程序里面的所有activity方法
     *
     * @param activity 返 回 类 型:void
     */
    public void addActivity(Activity activity)
    {
        listActivity.add(activity);
    }

    /**
     * 构造方法描述:退出程序方法
     * 返 回 类 型:void
     */
    public void exitApp()
{
    for (Activity activity : listActivity)
    {
        if (activity != null)
        {
            activity.finish();
        }
    }
    //清除USER登录缓存信息
    //GlobalTools.getInstance().saveObject(this, ConfigString.SAVE_USER_INFO_DATA,ConfigString.SP_NAME_SAVE_USER_INFO,null);

}
    public void exitAppExceptMain()
    {
        for (Activity activity : listActivity)
        {
            if (activity != null)
            {
                if (!MainActivity.class.getName().equals(activity.getClass().getName()))
                {
                    activity.finish();
                }
            }
        }
        //清除USER登录缓存信息
        //GlobalTools.getInstance().saveObject(this, ConfigString.SAVE_USER_INFO_DATA,ConfigString.SP_NAME_SAVE_USER_INFO,null);

    }


    /**
     * 初始化云推送通道
     * @param applicationContext
     */
    private void initCloudChannel(final Context applicationContext) {
        // 创建notificaiton channel
        this.createNotificationChannel();
        PushServiceFactory.init(applicationContext);
        final CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.i(TAG, "init cloudchannel success");
                //   Log.d("jjjjjjjjjjjjjjjjj","init cloudchannel success");
                // setConsoleText("");
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
                //setConsoleText("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
                //Log.d("jjjjjjjjjjjjjjjjjjjjjj", errorCode + " -- errorMessage:" + errorMessage);

            }
        });
        MiPushRegister.register(applicationContext, "XIAOMI_ID", "XIAOMI_KEY"); // 初始化小米辅助推送
        HuaWeiRegister.register(this); // 接入华为辅助推送
        VivoRegister.register(applicationContext);
        OppoRegister.register(applicationContext, "OPPO_KEY", "OPPO_SECRET");
        MeizuRegister.register(applicationContext, "MEIZU_ID", "MEIZU_KEY");

        GcmRegister.register(applicationContext, "send_id", "application_id"); // 接入FCM/GCM初始化推送


    }


    public static void setMainActivity(MainActivity activity) {
        mainActivity = activity;
    }



    public static void setConsoleText(String text) {
        if (mainActivity != null && text != null) {
            //  mainActivity.appendConsoleText(text);
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "1";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "notification channel";
            // 用户可以看到的通知渠道的描述
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }

    /**
     * 构造方法描述:销毁其他页面只留主MainAcivity
     * 返 回 类 型:void
     */
    public void exitActivitys()
    {
        //清除USER登录缓存信息
        GlobalTools.getInstance().saveObject(this, Configs.SAVE_LOGIN_KEY,Configs.SAVE_LOGIN_SP_NAME,null);
        for (Activity activity : listActivity)
        {
            if (activity != null)
            {
                if (!MainActivity.class.getName().equals(activity.getClass().getName()))
                {
                    activity.finish();
                }
            }
        }
        //给MainActivity发送消息，让其显示首页
        //    IntentTools.sendMassageMainActivity(0,null);

    }
    /***
     * 登录过期提示对话框
     * */
    public void showOpenLoginDialog(final Activity context)
    {
        exitActivitys();
        //清除USER登录缓存信息
        //GlobalTools.getInstance().saveObject(this, Configs.SAVE_LOGIN_KEY,Configs.SAVE_LOGIN_SP_NAME,null);
/*        Intent intent=new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);*/

/*       new AlertDialog.Builder(context).setTitle("提示").setMessage("登录已过期，是否重新登录?")
               .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                   {
                       exitActivitys();
                       startActivity(new Intent(context, LoginActivity.class));
        //销毁所有界面跳转到登录

                    }
               })
           .show();*/
    }

    public Bitmap getmScreenCaptureBitmap() {
        return mScreenCaptureBitmap;
    }


    public void setmScreenCaptureBitmap(Bitmap mScreenCaptureBitmap) {
        this.mScreenCaptureBitmap = mScreenCaptureBitmap;
    }


}
